//http://bj.58.com/ershoujiaju/
phantom.casperPath = 'D:\\phantomjs\\casperjs\\';
phantom.injectJs(phantom.casperPath + 'bin\\bootstrap.js');
//phantom.injectJs('jquery-1.7.2.js');
phantom.injectJs(phantom.casperPath + '..\\util\\cutil.js');

var casper = require('casper').create();

if (phantom.args.length === 0) {
    console.log('Usage: cartersjson.js <some URL>');
    phantom.exit();
} 
address = phantom.args[0];

casper.on('load.finished', function() {
    var page = this.page;
});

function getbaseInfo(jsonData) {
	
	if($("#index_show h1").length>0) {
		var title = $("#index_show h1")[0].textContent;
		jsonData.title = title;
	}
	if($("#divContacter .vcard li a ").length>0) {
		var userurl = $("#divContacter .vcard li a ")[0].href;
	}
	if($("#divContacter .vcard li a ").length>0) {
		var username = $("#divContacter .vcard li a ")[0].textContent;
		jsonData.username = username;
	}
	if($("#t_phone").length>0) {
		var tel = $("#t_phone")[0].childNodes[2].src;
	    jsonData.tel = tel;
	}
	if($(".qqnum .su_con img").length>0) {
		var qq = $(".qqnum .su_con img")[0].src;
	    jsonData.qq = qq;
	}
	
    jsonData.title = title;
    jsonData.username = username;
    jsonData.userurl = userurl;
    
    return jsonData;
}

casper.start();
casper.thenOpen(address, function() {
	/*
	var isnull = this.evaluate(waitUntilVisible, {
		selector : "#t_phone img",
		seconds : 6
	});
	if (isnull) {
		console.log('{[]}');
		return;
	}
	*/
	
    var page = this.page;
    var arr = new Array();
    var jsonData = {
        "title" : "",
        "url" : "",
        "username" : "",
        "userurl" : "",
        "tel" : "",
        "qq" : ""
    };
    
    jsonData = this.evaluate(getbaseInfo, {
    	jsonData : jsonData
    });

    if(jsonData.tel != null && jsonData.tel != "") {
    	var tel = jsonData.tel;
    	var fileName = "";
        var index = tel.indexOf("v=");
        fileName = tel.substring(index+2);
        this.download(tel, fileName+".jpg");
    }
    
    arr.push(jsonData);
    console.log(JSON.stringify(arr));
});


casper.run(function() {
    this.exit();
});

/** trim() method for String */
String.prototype.trim=function() {
	return this.replace(/(^\s*)|(\s*$)/g,'');
};

//http://bj.58.com/ershoujiaju/16601651416710x.shtml
